import React from "react";
import { View, Image, Text } from "@tarojs/components";
import Taro from "@tarojs/taro";
import { uploadFile } from "@/request/upload";
import { ShowLoading, HideLoading, VibrateShort } from "@/utils";

const ImgList: React.FC<{
    maxNum?: number,
    imgList: string[],
    upload?: boolean,
    preview?: boolean,
    onChange?: (urls: string[]) => void
}> = ({ imgList, upload, onChange, preview, maxNum }) => {
    const max = maxNum || 10
    const previewImg = (index, urls) => {
        if (preview) {
            Taro.previewImage({
                urls,
                current: index
            });
        }
    }
    const deleteImg = (index) => {
        VibrateShort()
        upload ? Taro.showModal({
            title: '是否删除所选图片？',
            content: '',
            success: (res: any) => {
                if (res.confirm) {
                    imgList.splice(index, 1)
                    onChange && onChange([...imgList])
                }
            }
        }) : null
    }
    const uploadImg = () => {
        Taro.chooseMedia({
            count: max - imgList.length,
            sourceType: ['album', 'camera'],
            sizeType: ['compressed'],
            success: (files) => {
                console.log(files.tempFiles);
                const requests = files.tempFiles.map(file => {
                    return uploadFile('/file/ossUpload', file.tempFilePath, { path: 'article-imgs/' })
                })
                ShowLoading('上传中')
                Promise.all(requests).then(results => {
                    const urls = results.map(res => res?.data?.url).filter(url => url)
                    if (typeof onChange === 'function') {
                        onChange([...imgList, ...urls])
                    }
                }).finally(() => {
                    HideLoading()
                  })
            }
        });
    }

    return (
        <View className="img-list-component flex-row flex-warp">
            {
                imgList.map((url, index) => {
                    return (
                        <Image className="img-item"
                            onLongPress={() => deleteImg(index)}
                            onClick={() => previewImg(index, imgList)}
                            src={url + '?x-oss-process=image/resize,m_fill,w_150,quality,q_60'}
                            key={url}
                            mode="aspectFill">
                        </Image>
                    )
                })
            }
            {
                upload && (max - imgList.length > 0) ? <View onClick={uploadImg} className="img-item add-img flex-row flex-center">
                    <Text className="iconfont icon-base-add"></Text>
                </View> : null
            }
        </View>
    )
}

export default ImgList